package com.mall.security;

import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * Token管理工具
 */@Component
public class TokenManager {

    //token有效时长(30分钟)
    public static long tokenEcpiration = 60*30*1000;

    //编码密钥
    public static  String tokenSignKey = "mima";

    //根据用户名生成token
    public static String createToken(String username) {
        String token = Jwts.builder()
                .setSubject(username)//设置token携带数据
                .setExpiration(new Date(System.currentTimeMillis() + tokenEcpiration))//token设置过期时间
                .signWith(SignatureAlgorithm.HS256, tokenSignKey)
                .compressWith(CompressionCodecs.GZIP).compact();
        return token;
    }

    //根据token字符串得到用户信息
    public static String getUserInfoFromToken(String token) throws ExpiredJwtException,IllegalArgumentException, MalformedJwtException {
        String userinfo = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token).getBody().getSubject();
        return userinfo;
    }

}
